package com.zte.cl.utils;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.zte.cl.entity.Field;
import com.zte.cl.model.News;
import com.zte.cl.parser.utils.SelectableUtil;

/**
 * 抽取工具类
 * @author lh
 *
 */
public class ExtractUtil {

	private static final Log log = LogFactory.getLog(ExtractUtil.class);
	
	/**
	 * 抽取内容并赋值到到news对象的属性上
	 * @param contentStr 待抽取的内容
	 * @param fields 待抽取的属性
	 * @param news news对象
	 * @return news是否有效
	 */
	public static boolean extractToNews(String contentStr, List<Field> fields, News news) {
		try {
			// 提取文章属性
			for (Field fd : fields) {
				String selVal = SelectableUtil.matchValue(contentStr, fd.getExprs());
				if (StringUtil.isEmpty(selVal) && fd.getRequired() != null
						&& fd.getRequired().equals("1")) {
					log.warn("没有抽取到必填属性"+fd.getName()+"的内容, 此条news无效!newsId:" + news.getId());
					return false;
				}else{
					selVal = SelectableUtil.replace(selVal, fd.getReplaces());
				}
				if (!StringUtil.isEmpty(fd.getDefaultValue())) {
					selVal = fd.getDefaultValue() + (selVal == null ? "" : selVal);
				}
				if (fd.getName().equals("publishTime")) {// 日期转换
					Date publishTime=DateUtil.parseTime(fd.getDateformat(), selVal);
					news.setPublishTime(publishTime);
				}else if(selVal!=null){
					BeanUtils.setProperty(news, fd.getName(), selVal);
				}
			}
		} catch (IllegalAccessException e) {
			log.error("抽取内容到news时发生错误!", e);
			return false;
		} catch (InvocationTargetException e) {
			log.error("抽取内容到news时发生错误!", e);
			return false;
		}
		return true;
	}
	
}
